package com.lkd.job;

import com.lkd.common.VMSystem;
import com.lkd.dao.TaskDao;
import com.lkd.entity.UserCountEntity;
import com.lkd.feign.UserService;
import com.lkd.vo.UserVO;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-08-21 10:47
 */
@Component
public class ComputeUserTask {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TaskDao taskDao;

    @XxlJob("computeUserTask")
    public ReturnT<String> workCountInitJobHandler(String param) {
        try {
            //获取每个人员未完成的工单数
            List<UserCountEntity> userIdTaskCount = taskDao.getUserIdTaskCount();
            //转换成map key是人员id value是工单数
            Map<Long, Long> collect = userIdTaskCount.stream()
                    .collect(Collectors.toMap(UserCountEntity::getUserId, UserCountEntity::getCount));

            List<UserVO> all = new ArrayList<>();
            List<UserVO> allOperators = userService.getAllOperators();
            List<UserVO> allRepairers = userService.getAllRepairers();
            all.addAll(allOperators);
            all.addAll(allRepairers);
            //工单初始化
            all.forEach(user -> {
                String key = VMSystem.generateUserTaskCountKey(user.getRegionId(),user.getRoleCode());
                //请补充完这段代码
                Long userId = user.getUserId().longValue();
                redisTemplate.opsForZSet().add(key,user.getUserId()
                        ,collect.containsKey(userId) ? collect.get(userId)  : 0);

                //1天之后过期
                redisTemplate.expire(key, Duration.ofDays(1));
            });
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            return ReturnT.FAIL;
        }
    }
}
